<template>
  <div class="infobox">
    <div class="topbox">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="患者姓名">
          <el-input clearable v-model="formInline.patientName" placeholder="" style="width: 180px" />
        </el-form-item>

        <el-form-item label="化验医院">
          <el-input clearable v-model="formInline.testHospital" placeholder="" style="width: 180px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button type="primary" @click="addbutton">新增</el-button>
          <el-button type="primary" @click="xgbutton">修改</el-button>
          <el-button type="primary" @click="deletebutton">删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table :data="datalist" border style="width: 100%" max-height="500" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="labTestItem" label="化验项" show-overflow-tooltip />
        <el-table-column prop="patientName" label="化验项ID" width="120" />
        <el-table-column prop="testHospital" label="项目名称" />
        <el-table-column prop="projectId" label="项目ID" />
        <el-table-column prop="status" label="状态" width="120" />
        <el-table-column prop="testHospital" label="单位" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="updateBy" label="记录人" width="120" />
        <el-table-column prop="updateTime" label="记录时间" />
        <!-- <el-table-column label="address">
          <template #default="scope">{{ scope.row.address }}</template>
        </el-table-column> -->
      </el-table>
      <div class="fybox">
        <el-pagination
          v-model:current-page="formInline.pageNum"
          v-model:page-size="formInline.pageSize"
          :page-sizes="[10, 50, 100, 200]"
          layout="total, sizes, prev, pager"
          :total="pagetotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="添加化验单" width="800" :before-close="handleClose">
      <el-form :model="formlist" label-width="auto" style="max-width: 700px">
        <el-form-item label="化验照片">
          <el-upload v-model:file-list="fileList" class="upload-demo" multiple :limit="1" :http-request="uploadFile">
            <el-button type="primary">上传图片</el-button>
            <template #tip>
              <div class="el-upload__tip"></div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="化验时间">
          <el-date-picker v-model="formlist.testTime" value-format="YYYY-MM-DD" type="date" style="width: 240px" />
        </el-form-item>
        <el-form-item label="化验医院">
          <el-select v-model="formlist.testHospital" placeholder="  " style="width: 100%">
            <el-option v-for="item in yylist" :key="item.value" :label="item.label" :value="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formlist.remark" />
        </el-form-item>
        <el-form-item label="化验项目">
          <el-select v-model="formlist.hyxm" multiple placeholder="  " style="width: 100%" @change="hyxulist">
            <el-option v-for="item in hyxmlist" :key="item.value" :label="item.label" :value="item.label" />
          </el-select>
        </el-form-item>

        <el-table v-if="showtable" :data="tableData" border style="width: 100%" :span-method="objectSpanMethod">
          <el-table-column prop="labTestItem" label="化验项目" width="120" />
          <el-table-column prop="projectName" label="项目" width="120" />
          <el-table-column label="结果" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-input v-model="scope.row.result"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-select v-model="scope.row.sx" placeholder="  " size="large" style="width: 240px">
                  <el-option
                    v-for="item in scope.row.dictList"
                    :key="item.dictCode"
                    :label="item.dictLabel"
                    :value="item.dictCode"
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单位">
            <!-- <el-input prop="unit"></el-input> -->
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-input v-model="scope.row.unit"></el-input>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savebutton"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { pLhyaddApi, updatehyjlApi, addhydApi, dehyjlApi, getListBylabTestItemId, uploadAPI } from "@/api/hzmange/index.js";
import { seekdataApi } from "@/api/system/system.js";
import { useRoute } from "vue-router";
let formlist = ref({});
const route = useRoute();
const useInfo = JSON.parse(sessionStorage.getItem("useInfo"));
const routedata = reactive(route.query);
const dialogVisible = ref(false);
let imgList = ref("");
let addxllist = ref([]);
const fileList = ref([]);
let formInline = ref({
  pageNum: 1,
  pageSize: 10,
  patientName: "",
  testHospital: ""
});
let xgstatus = ref(false);
let datalist = ref([]);
var pagetotal = ref(0);
const tableData = ref([]);
let showtable = ref(false);
let addbutton = () => {
  formlist.value = {};
  fileList.value = [];
  tableData.value = [];
  xgstatus.value = false;
  dialogVisible.value = true;
};
let selection = ref([]);
const handleSelectionChange = e => {
  selection.value = e;
};
const handleClose = () => {
  dialogVisible.value = false;
};

let uploadFile = val => {
  const fd = new FormData();
  fd.append("file", val.file);
  uploadAPI(fd).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "上传成功",
        type: "success"
      });
      imgList.value = res.url;
      formlist.value.photoUrl = res.url;
    } else {
      ElMessage({
        message: res.msg,
        type: "error"
      });
    }
  });
};

let savebutton = () => {
  //修改
  if (xgstatus.value == true) {
    updatehyjlApi(ruleForm.value).then(() => {
      ElMessage({
        message: "修改成功",
        type: "success"
      });

      dialogVisible.value = false;
      xgstatus.value = false;
      //刷新列表数据
      getlist();
    });
  } else {
    //新增
    let addparam = {
      patientName: routedata.name, //患者姓名
      patientId: routedata.id, //患者ID
      testTime: formlist.value.testTime, //化验时间
      testHospital: formlist.value.testHospital, //化验医院
      photoUrl: formlist.value.photoUrl, //化验单照片URL
      tbPatientLabHistoryDetailList: tableData.value,
      remark: formlist.value.remark //备注
    };
    addhydApi(addparam).then(() => {
      ElMessage({
        message: "新增成功",
        type: "success"
      });
      dialogVisible.value = false;
      getlist();
    });
  }
};
const spanArr = ref([]);
const pos = ref(0);
const getSpanArr = data => {
  spanArr.value = [];
  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      spanArr.value.push(1);
      pos.value = 0;
    } else {
      // 判断当前元素与上一个元素是否相同
      if (data[i].labTestItem === data[i - 1].labTestItem) {
        spanArr.value[pos.value] += 1;
        spanArr.value.push(0);
      } else {
        spanArr.value.push(1);
        pos.value = i;
      }
    }
  }
};

// 合并方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    const _row = spanArr.value[rowIndex];
    const _col = _row > 0 ? 1 : 0;
    return {
      rowspan: _row,
      colspan: _col
    };
  }
};
var tablelist = [];
//下拉化验项目单子,选出对用的项目
let hyxulist = e => {
  let YPlist = JSON.parse(sessionStorage.getItem("YPlist"));
  let checkdata = e.flatMap(key => YPlist[key] || []);
  tableData.value = checkdata;
  // 合并单元格方法调用
  getSpanArr(tableData.value);
  showtable.value = true;
  console.log("tableData=======>", tableData.value); // 所有数据加载完成后打印
};

let handleSizeChange = () => {
  formInline.value.pageNum = 1;
  getList();
};
let handleCurrentChange = () => {
  getList();
};
// 初始化数据
getList();
// 获取数据
function getList() {
  pLhyaddApi(formInline.value).then(res => {
    datalist.value = res.rows;
    pagetotal.value = res.total;
  });
}

getYZlsit();
let hyxmlist = ref([]);
let yylist = ref([]);
function getYZlsit() {
  seekdataApi({ dictType: "sys_laboratory_item" }).then(res => {
    hyxmlist.value = res.data.map(item => ({
      value: item.dictValue,
      label: item.dictLabel
    }));
  });

  seekdataApi({ dictType: "sys_hospital_name" }).then(res => {
    yylist.value = res.data.map(item => ({
      value: item.dictValue,
      label: item.dictLabel
    }));
  });

  seekdataApi({ dictType: "sys_laboratory_status_" }).then(res => {
    addxllist.value = res.data.map(item => ({
      value: item.dictValue,
      label: item.dictLabel
    }));
  });
}
const xgbutton = () => {
  if (selection.value.length == 1) {
    getListBylabTestItemId({
      patientId: selection.value[0].patientId
    }).then(res => {
      dialogVisible.value = true;
      tableData.value = res.data;
      xgstatus.value = true;
      showtable.value = true;
    });
  } else {
    ElMessage({
      message: "请选择一条数据",
      type: "warning"
    });
  }
};
const deletebutton = () => {
  if (selection.value.length == 1) {
    ElMessageBox.confirm("确定删除?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      dehyjlApi({
        id: selection.value[0].id
      }).then(res => {
        ElMessage({
          type: "success",
          message: `${res.msg}`
        });
        getList();
      });
    });
  } else {
    ElMessage({
      message: "请选择一条数据",
      type: "warning"
    });
  }
};
</script>

<style lang="scss" scoped>
.topbox {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 10px;
}
.tableboxs {
  height: 500px;
  overflow: auto;
}

.hydbox {
  display: flex;
  align-items: center;
}
.infobox {
  height: 400px;
  overflow: auto;
}
.fybox {
  display: flex;
  justify-content: end;
}
</style>
